const id = (() => {
    let y = getQueryVariable('tid');
    let x = parseInt(y);
    console.log(y, x);
    return isNaN(x) ? null : x;
})();
const tags = new Set();
$(() => {
    const t = $("#editor_btn");
    const d = [
        ['attach', '附件'],
        ['bold', '加粗'],
        ['expand', '全屏'],
        ['image', '图片'],
        ['insert_tag_field', '代码'],
        ['italic', '斜体'],
        ['link', '链接'],
        ['remove_link', '删除链接'],
        ['quotation_marks', '引用'],
        ['remove_formatting', '删除格式'],
        ['richtextbulletedlist', '无序列表'],
        ['richtextnumberedlist', '有序列表'],
        ['strikethrough', '删除线'],
        ['underline', '下划线'],
    ];
    for (let x in d) {
        x = d[x];
        t.append(`<button data-name="${x[0]}"onclick="replaceInput(editFunc.${x[0]},this);" type="button"class="btn btn-default"title="${x[1]}"><svg class="icon"aria-hidden="true"><use xlink:href="#icon-${x[0]}"></use></svg></button>`)
    }
    document.addEventListener('mousedown', e => /*禁止功能按钮获取焦点, 以防止输入框失去焦点*/
        $(e.target).parents('#editor_btn').length && e.preventDefault());
    if (id) {
        $.get(`/threads/get?tid=${id}`, r => {
            if (r && r.success) {
                r = toRealName(r.result);
                $("#input_title").val(r.title);
                $("#input_field").val(r.content);
                flushContent();
            } else errorHandle(r.err);
        });
        $.get(`/threads/tags?tid=${id}`, r => {
            if (r && r.success) {
                r = r.result;
                let tar = $("#tags").html('');
                tags.clear();
                for (let x in r) {
                    x = toRealName(r[x]);
                    tags.add(x.id);
                    tar.append(`<span onclick="useTag(-${x.id})" class="capsule small tag-id-${x.id}"title="${x.id} - ${new Date(x.quote).toLocaleString()}">#${x.name}</span>`)
                }
            } else errorHandle(r.err);
        })
    } else {
        $("#input_title").val(localStorage.getItem('editor.html_autoSave-title'));
        $("#input_field").val(localStorage.getItem('editor.html_autoSave-content'));
        let TAGS = localStorage.getItem('editor.html_autoSave-tags');
        if (TAGS) $.get(`/threads/tags`, { tags: TAGS }, r => {
            if (r && r.success) {
                r = r.result;
                let tar = $("#tags").html('');
                tags.clear();
                for (let x in r) {
                    x = toRealName(r[x]);
                    tags.add(x.id);
                    tar.append(`<span onclick="useTag(-${x.id})" class="capsule small tag-id-${x.id}"title="${x.id} - ${new Date(x.quote).toLocaleString()}">#${x.name}</span>`)
                }
            } else errorHandle(r.err);
        });
        search_tag(localStorage.getItem('editor.html_autoSave-tags-s'));
    }
});
const editFunc = {
    attach: x => {},
    expand: x => null,
    image: inputRequest(["注释", { n: '上传图片', t: 'file' }], async (l, f) => await uplaodImg(l, f.files[0], (err, uid) => err ? ` __上传图片失败__ ${err}` : `![${l}](${uid})`)),
    insert_tag_field: x => {},
    link: inputRequest(['链接地址', '链接名称'], (l, n) => l ? (n ? `[${n}](${l})` : `<${l}>`) : null),
    remove_link: x => {},
    quotation_marks: x => {},
    remove_formatting: x => {},
    richtextbulletedlist: x => editLine(x, y => `+ ${y}`),
    richtextnumberedlist: x => editLine(x, (y, i) => `${i+1}. ${y}`),
    underline: x => `<u>${x}</u>`,
    bold: x => ` __${x}__ `,
    italic: x => ` _${x}_ `,
    strikethrough: x => `~${x}~`,
}
async function editLine(x, func) {
    let data = x.split('\n');
    for (let i in data) data[i] = await func(data[i], parseInt(i));
    data = `\n${data.join("\n")}\n\n`;
    return data;
}
async function replaceInput(func, target) {
    let SHAKE = () => shake($(target), 2, Math.random() * 3 + 3, 150);
    let t = document.activeElement;
    if (t.id !== 'input_field') return SHAKE() && false;
    if (window.getSelection) {
        let s = t.selectionStart;
        let e = t.selectionEnd;
        if (isNaN(s) || isNaN(e)) return null;
        let text = t.value;
        let sub = text.substring(s, e);
        let new_sub = await func(sub, target);
        console.log('replaceInput', new_sub);
        if (!new_sub) return SHAKE();

        t.value = text.substring(0, s) + new_sub + text.substring(e);
        t.selectionStart = s;
        t.selectionEnd = e + new_sub.length - sub.length;
        flushContent();
        return true;
    }
    return null;
}

function inputRequest(request, summer) {
    return async (select, target) => {
        return new Promise(r => {
            let offset = (target = $(target)).offset();
            let tar = $(`<div class="inputRequest"id="${target.attr('data-name')}-input">`).css('left', offset.left).css('top', offset.top + target.outerHeight());
            request.forEach(e => tar.append(typeof e === 'string' ? `<span>${e}</span><input type="text" placeholder="${e}"/>` : `<span>${e.n}</span><input ${e.e||''} type="${e.t}" placeholder="${e.n}"/>`));
            tar.children('input').val(select);
            $('<button type="button"class="btn btn-default">').html('完成').click(async x => {
                x = $(x.target).parent();
                let c = x.children('input');
                c.each((i, e) => e.type === 'text' && (c[i] = e.value));
                x.remove();
                r(await summer(...c));
            }).appendTo(tar);
            tar.appendTo($('body'));
            tar = tar.attr('id');
            $('body').mousedown(x => {
                if (x.target.id === tar || $(x.target).parents('#' + tar).length > 0) return;
                $("#" + tar).remove();
                r(null);
            })
        })
    }
}

async function uplaodImg(lore, file, summer) {
    return new Promise(resolve => {
        uploadFile(file, 'thread-img', req => {
            req.setRequestHeader("x-lore", lore);
        }, r => {
            if (!r.success) console.log('uploadImg', r.err);
            cacheImg.push(r.result);
            resolve(summer(r.err, '/img/thread/' + r.result));
            return true;
        });
    });
}

function flushContent() {
    $("#output_field").html(marked($("#input_field").val()));
    savePage();
}
/** 摇晃对象
 * @param T 对象
 * @param a 次数
 * @param d 距离
 * @param t 时间
 * */
function shake(T, a, d, t) {
    if (!T || !T.length) return false;
    T.css({ position: 'relative' });
    for (let x = 1; x <= a; x++) {
        let lr = Math.random() > 0.5 ? d : -d,
            tb = Math.random() > 0.5 ? d : -d;
        T.animate({ left: -lr, top: -tb }, (((t / a) / 4)))
            .animate({ left: lr, top: tb }, ((t / a) / 2))
            .animate({ left: 0, top: 0 }, (((t / a) / 4)));
    }
    return true;
}
const cacheImg = [];

function savePage() {
    localStorage.setItem('editor.html_autoSave-title', $("#input_title").val() || "");
    localStorage.setItem('editor.html_autoSave-content', $("#input_field").val() || "");
    localStorage.setItem('editor.html_autoSave-tags', [...tags].join() || "");
    localStorage.setItem('editor.html_autoSave-tags-s', search_tag_last || "");
}

function finish() {
    let title = $("#input_title").val();
    let content = $("#input_field").val();
    localStorage.removeItem('editor.html_autoSave-title');
    localStorage.removeItem('editor.html_autoSave-content');
    localStorage.removeItem('editor.html_autoSave-tags');
    localStorage.removeItem('editor.html_autoSave-tags-s');
    $.ajax({
        type: "POST",
        url: "/upload/threads",
        cache: 'false',
        data: { title: title, content: content, tid: id, tags: [...tags].join() },
        complete: res => {

            console.log(res);
            res = res.responseJSON || {};
            if (res.success) {
                let tit = ($.ajax({
                    url: "/upload/thread-img-tid",
                    async: false,
                    type: "POST",
                    data: { imgs: cacheImg.join(','), tid: res.result }
                })).responseJSON;
                if (tit && tit.success) alert(`成功${id?'编辑':'创建'} ${res.result} 号帖子!`);
                else alert(`成功${id?'编辑':'创建'} ${res.result} 号帖子!\n但绑定图片时出错:${res.result.join()}`)
                window.location.href = '/public/threads.html?tid=' + res.result;
            } else if (res.message) alert(res.message);
            else {
                console.log("/threads/upload", res.err);
                alert(`发生错误:\n${res.err}\n请检查!`);
            }
        }
    });
    cacheImg.forEach(e => {

    });
}

let search_tag_last;
let search_tag_result;
/**搜索标签*/
function search_tag(val) {
    if (search_tag_last === val) return;
    search_tag_last = val;
    if (!val) {
        $("#tags_editor").html('');
        return;
    }
    $("#search_input").val(val);
    $.get("/threads/search-tag/" + val, r => {
        if (r.success) {
            $("#tags_editor").html('');
            search_tag_result = r = r.result;
            for (let k in r) {
                $("#tags_editor").append(`<span onclick="useTag(${k})" class="capsule small"title="${k}">#${r[k]}</span>`)
            }
        }
    });
    savePage();
}

/**
 * 使用标签
 * @param id 标签ID, 使用ID的负数来移除tag
 * */
function useTag(id) {
    if (id < 0) {
        tags.delete(-id);
        $(`#tags .tag-id-${-id}`).remove();
    } else if (!tags.has(id)) {
        tags.add(id);
        $("#tags").append(`<span onclick="useTag(-${id})" class="capsule small tag-id-${id}"title="${id} - ${new Date().toLocaleString()}">#${search_tag_result[id]}</span>`)
    }
    savePage();
}